package com.lagou.demo.handler;

import com.lagou.edu.mvcframework.LagouHandlerInterceptor;
import com.lagou.edu.mvcframework.annotations.Security;
import com.lagou.edu.mvcframework.pojo.Handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zhangxin
 * @date 2021/5/18
 * @description TODO 此处添加class描述
 */
public class UserAuthInterceptor implements LagouHandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Handler theHandler = (Handler) handler;
        Security annotation = theHandler.getMethod().getAnnotation(Security.class);
        if(annotation!=null){
            String[] value = annotation.value();
            String[] usernames = request.getParameterValues("username");
            if(usernames!=null&&usernames.length>0){
                for (String s : value) {
                    if(s.equals(usernames[0])){
                        return true;
                    }
                }
            }
            response.getWriter().write("401 no access!");
        }
        return false;
    }
}
